//引入express模块
const express = require('express');
const cors = require('cors')
//引入数据库连接模块
const pool = require('../pool.js');
//创建路由器对象
const r = express.Router();
//添加路由
const jwt = require('jsonwebtoken');
// const { id } = require('element-plus/es/locale/index.js');
const secret = "secret";
const exp = '1800s';


// 添加账号
r.post('/addaccount', (req, res, next) => {
    let data = req.body.data.split(",").filter(item => item.trim() !== '')
    // console.log(data);
    let results = {
        success: 0,
        error: 0,
        all: 0
    };
    // console.log(data);

    data.forEach((name, index) => {
        setTimeout(() => {
            pool.query(`SELECT * FROM lutian_account WHERE account = '${name}'`, (err, r) => {
                if (err) {
                    results.all += 1
                    results.error += 1
                    // console.log(index + 1, data.length);
                    // console.log(results.all, data.length);
                    if (index + 1 == data.length && results.all == data.length) {
                        res.send({ code: 200, msg: "添加账号成功", data: results })
                    }
                } else {
                    // console.log(r);
                    if (r.length > 0) {
                        results.all += 1
                        results.error += 1
                        // console.log(index + 1, data.length);
                        // console.log(results.all, data.length);
                        if (index + 1 == data.length && results.all == data.length) {
                            res.send({ code: 200, msg: "添加账号成功", data: results })
                        }
                    } else {
                        pool.query(`insert into lutian_account set account="${name}"`, (err, r) => {
                            if (err) {
                                results.all += 1
                                results.error += 1
                                // console.log(index + 1, data.length);
                                // console.log(results.all, data.length);
                                if (index + 1 == data.length && results.all == data.length) {
                                    res.send({ code: 200, msg: "添加账号成功", data: results })
                                }
                            } else {
                                results.all += 1
                                results.success += 1
                                // console.log(index + 1, data.length);
                                // console.log(results.all, data.length);
                                if (index + 1 == data.length && results.all == data.length) {
                                    res.send({ code: 200, msg: "添加账号成功", data: results })
                                }
                            }
                        })
                    }
                }
            })
        }, 10 * index);

    });

})

// 根据条件查询账号
r.get('/saveAccountlist', (req, res, next) => {
    let keyword = req.query.keyword;
    let pagesize = req.query.pagesize;
    let currentpage = req.query.currentpage - 1;
    let sqlstr = 'select * from lutian_account'
    let sqlstr2 = 'select * from lutian_account'
    let sqlarr = []
    if (keyword != '' && keyword != undefined) {
        // sqlarr.push(`(account LIKE '%${keyword}%')`)
        sqlstr += " WHERE " + `(account LIKE '%${keyword}%')`
        sqlstr2 += " WHERE " + `(account LIKE '%${keyword}%')`
    }
    if (currentpage == 0) {
        sqlstr += ` LIMIT ${pagesize}`;
    } else {
        sqlstr += ` LIMIT ${pagesize} OFFSET ${pagesize * currentpage}`;
    }
    pool.query(sqlstr, (err, r) => {
        if (err) {
            next(err);
            return;
        } else {
            // res.send({ code: 200, msg: "查询成功", data: r });
            pool.query(sqlstr2, (err2, r2) => {
                if (err2) {
                    //抛出错误，阻止后边程序的执行，用于调试
                    //throw err;
                    //交给下一个错误处理中间件，同时把错误信息传递过去
                    next(err2);
                    //阻止往后执行
                    return;
                }
                res.send({ code: 200, msg: "查询成功", data: r, total: r2.length, pagesize: pagesize, currentpage: currentpage + 1 });
            });
        }
    })


})

// 查询全部账号
r.get('/saveAllAccountlist', (req, res, next) => {
    let keyword = req.query.keyword;
    let sqlstr = 'select * from lutian_account'
    if (keyword != '' && keyword != undefined) {
        sqlstr += " WHERE " + `(account LIKE '%${keyword}%')`
    }
    pool.query(sqlstr, (err, r) => {
        if (err) {
            next(err);
            return;
        } else {
            res.send({ code: 200, msg: "查询全部账号成功", data: r });
           
        }
    })

})

// 删除账号
r.post('/deleteAccount', (req, res, next) => {
    const id= parseInt(req.body.id)
    const msql = `delete from lutian_account where id = ${id}`;
    pool.query(msql, (err, r) => {
        if (err) {
            next(err)
            return;
        }
        res.send({ code: 200, msg: "删除成功" });
    })

})

// 修改用户绑定账号
r.post('/setuserAccount', (req, res, next) => {
    const userId = req.body.userId;
    const accounts = req.body.accounts;
    const accountsname = req.body.accountsname;
    const mysql = `update lutian_user set accounts = '${accounts}',accountsname = '${accountsname}' WHERE userId = ${userId}`;
    pool.query(mysql, (err, r) => {
        if (err) {
            next(err)
            return;
        } else {
            res.send({ code: 200, msg: '修改用户绑定账号成功', data: r });
        }
    })

})







//暴露出去
module.exports = r;